package org.jeecg.modules.dd.controller;

import com.alibaba.druid.util.DaemonThreadFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.test.entity.JeecgDemo;
import org.jeecg.modules.demo.test.service.IJeecgDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import com.dingtalk.api.request.OapiChatSendRequest.Link;
import com.dingtalk.api.request.OapiChatSendRequest.Msg;
import org.jeecg.modules.dd.config.ApplicationConfig;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/dd")
@Component
public class DLogin extends JeecgController<JeecgDemo, IJeecgDemoService> {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ApplicationConfig applicationConfig;

    private String getToken() throws ApiException {

        System.out.println("获取token------------------------------");
        System.out.println(applicationConfig.getClientId());
        System.out.println(applicationConfig.getClientSecret());
        System.out.println("获取token------------------------------------");

        String access_token = (String) redisUtil.get("cndkToken");
        if (!StringUtils.isEmpty(access_token)) {
            return access_token;
        } else {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(applicationConfig.getClientId());
            request.setAppsecret(applicationConfig.getClientSecret());
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
//            Map<String, String> map = JSONObject.parseObject(response.getBody(), Map.class);
            JSONObject object = JSONObject.parseObject(response.getBody());
            redisUtil.set("cndkToken", object.get("access_token"));
            redisUtil.expire("cndkToken", 7200);
            return object.getString("access_token");
        }

    }

    //    获取jsapiTicket
    private void getJsapiTicket() throws ApiException {
        String ticket = (String) redisUtil.get("cndkticket");
        if (!StringUtils.isEmpty(ticket)) {
//            return ticket;
        } else {
            String access_token = getToken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
            OapiGetJsapiTicketRequest req = new OapiGetJsapiTicketRequest();
            req.setHttpMethod("GET");
            OapiGetJsapiTicketResponse rsp = client.execute(req, access_token);
            System.out.println(rsp);
            JSONObject object = JSONObject.parseObject(rsp.getBody());
            redisUtil.set("cndkticket", object.get("ticket"));
            redisUtil.expire("cndkticket", 7200);
//            return (String) object.get("cndkticket");
        }
    }

    @GetMapping("/a")
    public String test() throws ApiException {
        String access_token = getToken();
        getJsapiTicket();
        return access_token;
    }


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(@RequestParam("code") String code) throws ApiException {
        String access_token = getToken();
        getJsapiTicket();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
        OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
        req.setCode(code);
//        Map<String, String> map = JSONObject.parseObject(access_token, Map.class);
        OapiV2UserGetuserinfoResponse rsp = client.execute(req, access_token);
//        JSONObject object= JSONObject.parseObject(rsp.getBody());
        return rsp.getBody();
    }

    //    详细信息
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public String getUserInfo(String userid) {
        try {
            String access_token = getToken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userid);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = client.execute(req, access_token);
            System.out.println(rsp.getBody());
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
            return "";
        }
    }
//    获取部门列表
    @GetMapping("/getDeptList")
    public String getDeptList(String deptId) throws ApiException {
        String access_token = getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
            OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
            req.setDeptId(Long.valueOf(deptId));
            OapiV2DepartmentGetResponse rsp = client.execute(req, access_token);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 通过定时任务发送打卡消息通知
     * @return Result<T>
     */
    //每天早上09点送一次，下午17点发送一次
//    @Scheduled(cron = "0 00 9,17 * * ?")
    private void sendMessage() {
        try {
            String token = getToken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.setAgentId(applicationConfig.getAgentId());
            Set<String> userIdList = getUserIdList();
            for (String userId : userIdList) {
                req.setUseridList(userId);
                Msg obj1 = new Msg();
                obj1.setMsgtype("link");
                Link obj2 = new Link();
                obj2.setPicUrl("C:/Users/86199/Pictures/Saved Pictures/1.jpg");
                obj2.setMessageUrl("http://"+applicationConfig.getIpAddress()+":3000/?corpId=$COPRID$");
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formatDate = dateFormat.format(date);
                obj2.setTitle(formatDate+":项目打卡通知");
                obj2.setText("点此进行打卡");
                obj1.setLink(obj2);
                req.setMsg(JSON.toJSONString(obj1));
                OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, token);
                System.out.println(rsp.getBody());
                System.out.println("发送任务");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据根部门id获取所有子部门id
     * @return
     */

    private List<Long> getDeptList(){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsubid");
            OapiV2DepartmentListsubidRequest req = new OapiV2DepartmentListsubidRequest();
            req.setDeptId(1L);
            OapiV2DepartmentListsubidResponse rsp = client.execute(req, getToken());
            System.out.println(rsp.getBody());
            List<Long> deptIdList = rsp.getResult().getDeptIdList();
            return deptIdList;
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据子部门id获取部门下的所有用户id，并将用户id放入set集合中防止重复
     * @return
     */

    private Set<String> getUserIdList(){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
            OapiUserListidRequest req = new OapiUserListidRequest();
            List<Long> deptIdList = getDeptList();
            Set<String> useridSet=new HashSet<>();
            for (Long deptId : deptIdList){
                req.setDeptId(deptId);
                OapiUserListidResponse rsp = client.execute(req, getToken());
                List<String> useridList = rsp.getResult().getUseridList();
                useridSet.addAll(useridList);
            }
            return useridSet;
        } catch (ApiException e) {
            e.printStackTrace();
            return  null;
        }
    }
}


